#include "CTextureAnimation.h"
#include "CTextureAnimationProp.h"
#include "CVector3.h"
#include "CVector2.h"
#include "WareArithmetic.h"

BEGIN_WARE

CTextureAnimation::CTextureAnimation( IEffectUnitProp* pEffectUnitProp )
: CEffectUnit( pEffectUnitProp )
{
}

CTextureAnimation::~CTextureAnimation(void)
{
}

void CTextureAnimation::CullVisibleObjects( IGraphic* pGraphic, ISceneNodeCamera* pCamera )
{
	m_Sprite.CullVisibleObjects( pGraphic, pCamera );
}

VBOOL CTextureAnimation::Update( IGraphic* pGraphic, const CMatrix4& MatParent, uint32 uCurTime )
{
	CTextureAnimationProp* pProp = (CTextureAnimationProp*)m_pEffectUnitProp;

	float32 fElapseTime = static_cast<float32>( uCurTime - m_uStartTime );
	float32 fTotalTime = static_cast<float32>( pProp->m_nTotalTime );
	float32 fPos = fElapseTime / fTotalTime;
	fPos = WareMath::Tail( fPos );

	ITexture* pTex = NULL;
	GetMapValue( m_mapTexture, fPos, pTex );
	//if( pTex )
	m_Sprite.SetTexture( pTex );

	CVector3 pos;
	GetMapLinearLerpValue( pProp->m_mapOffset, fPos, pos );
	m_Sprite.SetOffset( CVector2( pos[0], pos[1] ) );

	float32 fSize = 0.0f;
	GetMapLinearLerpValue( pProp->m_mapSize, fPos, fSize );
	m_Sprite.SetWidth( static_cast<int32>( pProp->m_nWidth * fSize + 0.5f ) );
	m_Sprite.SetHeight( static_cast<int32>( pProp->m_nHeight * fSize + 0.5f ) );

	float32 fAlpha = 0.0f;
	GetMapLinearLerpValue( pProp->m_mapAlpha, fPos, fAlpha );
	m_Sprite.SetAlpha( VTRUE, static_cast<uint8>( fAlpha * 255.0f + 0.5f ) );

	m_Sprite.Update( pGraphic, uCurTime );

	return VFALSE;
}

VBOOL CTextureAnimation::Render( IGraphic* pGraphic, uint32 uCurTime )
{
	return m_Sprite.Render( pGraphic, uCurTime );
}

VBOOL CTextureAnimation::Create( IResourceManager* pResMgr )
{
	CTextureAnimationProp* pProp = (CTextureAnimationProp*)m_pEffectUnitProp;
	
	CEffectUnit::Create( pResMgr );

	m_Sprite.CreateSprite();
	m_Sprite.SetWidth( pProp->m_nWidth );
	m_Sprite.SetHeight( pProp->m_nHeight );
	m_Sprite.SetAlpha( VTRUE, 255 );

	return VTRUE;
}

void CTextureAnimation::SetEffectUnitProp( IEffectUnitProp* pProp )
{
	//CTextureAnimationProp* p = (CTextureAnimationProp*)m_pEffectUnitProp;
	
	m_Sprite.SetTexture( NULL );

	CreateTexture();
}

END_WARE
